<template>
  <view class="cu-modal bottom-modal" :class="{ show: showAuth }" @tap="closeAuthModal" style="z-index: 10080;">
    <view class="login-wrap cu-dialog form-wrap  safe-area-inset-bottom"
          v-if="authType === 'accountLogin'" @tap.stop style="
          border-radius: 20rpx 20rpx 0 0;min-height: 440rpx;">
      <!-- 第三方登录 -->
      <view v-if="authType === 'accountLogin' || authType === 'smsLogin'" class="auto-login-box u-flex u-row-center u-col-center">
        <view @tap="thirdLogin('wechat')" v-if="['App', 'wxOfficialAccount', 'wxMiniProgram'].includes(platform)">
          <!-- 微信 -->
          <image
              class="auto-login-img"
              :src="$IMG_URL + '/imgs/auto_login_wx.png'"
          ></image>
          <view>微信登录</view>
        </view>
      </view>
      <!-- 协议 -->
      <view class="agreement-box u-flex u-row-left">
        <u-checkbox v-model="protocol" shape="circle" active-color="#E9B461">
          <view class="agreement-text tcp-text u-flex u-row-left">
            我已阅读并遵守
            <view class="tcp-text u-flex u-col-center">
              <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initShop.user_protocol || 0 } })">《用户协议》</view>
              与
              <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initShop.privacy_protocol || 0 } })">《隐私协议》</view>
            </view>
          </view>
        </u-checkbox>
      </view>
    </view>

    <view v-else class="login-wrap cu-dialog form-wrap  safe-area-inset-bottom" v-if="authType === 'bindMobile'"  @tap.stop style="border-radius: 20rpx 20rpx 0 0;">
      <view class="avatar_box">
        <view class="join_us" >完善信息</view>
        <view class="get_avatar">
          <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" slot="right"
                  style="background-color: initial;line-height: initial;padding-left: 0;padding-right: 0;
					width: 300rpx;display: flex;justify-content: flex-end;">
            <image v-if="form['bindMobile'].data.avatar!==''" class="avatar" :src="form['bindMobile'].data.avatar"></image>
            <view v-else class="avatar">编辑头像</view>
            <view class="text">一键获取</view>
          </button>
        </view>
      </view>
      <view class="login_input">
        <view class="item">
          <view class="item_l">
            <view class="item_l_tit">昵称</view>
            <input type="nickname" :value="form['bindMobile'].data.nickname" placeholder="请输入昵称" @blur="userNameInput">
          </view>
        </view>
        <view class="item">
          <view class="item_l">
            <view class="item_l_tit">手机号</view>
            <input type="text"
                   @blur="checkValue($event, 'mobile')"
                   @input="mobileInput($event, 'mobile')"
                   v-model="form['bindMobile'].data.mobile"
                   placeholder="请输入手机号码">
            <view class="note">{{ form['bindMobile'].error.mobile || '' }}</view>
          </view>
          <view class="item_r">
            <button open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">
              一键填写
            </button>
          </view>
        </view>
      </view>

      <view class="join_float">
        <view class="join_confirm" @tap="bindMobileSubmit()">完善信息</view>
      </view>

      <!-- 协议 -->
      <view class="agreement-box u-flex u-row-left">
        <u-checkbox v-model="protocol" shape="circle" active-color="#E9B461">
          <view class="agreement-text tcp-text u-flex u-row-left">
            我已阅读并遵守
            <view class="tcp-text u-flex u-col-center">
              <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initShop.user_protocol || 0 } })">《用户协议》</view>
              与
              <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initShop.privacy_protocol || 0 } })">《隐私协议》</view>
            </view>
          </view>
        </u-checkbox>
      </view>
    </view>

  </view>
</template>

<script>
/**
 * 登录提示页
 */
import FormValidate from '@/shopro/validate/form';
import schema from '@/uview-ui/libs/util/async-validator';
import wechat from '@/shopro/wechat/wechat';
import Auth from '@/shopro/permission/index.js';
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
// #ifdef APP-PLUS
import apple from '@/shopro/apple';
// #endif

export default {
  name: 'shoproAuthModal',
  data() {
    return {
      platform: this.$platform.get(),
      device: this.$platform.device(),
      form: {
        // 5.绑定手机号
        bindMobile: {
          data: {
            nickname: '',
            avatar: '',
            avatarUrl: '',
            mobile: '', //手机号
            // code: '', //验证码
            isMobileEnd: false // 手机号输入完毕
          },
          rules: {
            // code: FormValidate.code,
            mobile: FormValidate.mobile
          },
          error: {
            mobile: '', //手机号
            // code: '' //验证码
          }
        },
      },
      codeText: '获取验证码',
      disabledCode: false,
      protocol: false, //是否同意隐私协议
      placeholderStyle: 'font-size: 30rpx; font-weight: 500;color: #444;'
    };
  },

  computed: {
    ...mapGetters(['initShop', 'isLogin', 'authType']),
    showAuth: {
      get() {
        return !!this.authType;
      },
      set(value) {
        value ? uni.hideTabBar() : uni.showTabBar();
      }
    }
  },
  mounted() {
  },
  methods: {
    ...mapActions(['getUserInfo', 'showAuthModal']),

    // 修改昵称
    userNameInput(e) {
      let that = this;
      that.form['bindMobile'].data.nickname = e.detail.value
    },

    // 更换头像
    async onChooseImg() {
      let authState = 0;
      authState += await new Auth('writePhotosAlbum').check();
      if (authState < 1) return;
      authState += await new Auth('camera').check();
      if (authState < 2) return;
      const chooseImageRes = await this.chooseImage(1);
      const uploadImageRes = await this.uploadImage(chooseImageRes[0]);
      this.form['bindMobile'].data.avatar = uploadImageRes.fullurl;
    },

    onChooseAvatar(e) {
      let that = this
      uni.uploadFile({
        url: that.$API_URL + 'index/upload',
        filePath: e.detail.avatarUrl,
        name: 'file',
        success: res => {
          res = JSON.parse(res.data);
          if (res.code === 1) {
            console.log(res.data)
            this.form['bindMobile'].data.avatar = res.data.fullurl;
            this.form['bindMobile'].data.avatarUrl = res.data.url;

            that.$u.toast('上传成功');
          } else {
            that.$u.toast('上传失败');
          }
        },
        complete: e => {
          uni.hideLoading();
        }
      });
    },

    // 微信小程序手机号授权登录
    async decryptPhoneNumber(e){
      let that = this;

      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin',
        success: res => {
          that.$http(
              'user.decryptPhoneNumber',
              {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
                code: res.code
              },
              '绑定中...'
          )
              .then(result => {
                that.form['bindMobile'].data.mobile = result.data.phoneNumber;
                that.form['bindMobile'].data.isMobileEnd = true;
                that.validation('bindMobile');
              });
        },
        fail: err => {
          console.log(err)
        }
      });
      // #endif
    },

    closeAuthModal() {
      this.$store.dispatch('showAuthModal', '');
    },

    // 第三方登录
    async thirdLogin(provider) {
      const that = this;
      let token = '';
      switch (provider) {
        case 'wechat':
          token = await wechat.login();
          break;
        case 'alipay':
          break;
        case 'apple':
          token = await apple.appleIdOauth();
          break;
        default:
          break;
      }
      if (token) {
        // that.closeAuthModal();
        that.getUserInfo(token);
      }
    },

    // 校验数据
    validation(key, callback = () => {}) {
      let that = this;
      //拿到需要校验的数据
      let fieldValue = this.form[this.authType].data[key];
      //拿到需要检验的规则
      let rules = this.form[this.authType].rules[key];
      // 判空
      if (!rules || rules.length === 0) {
        return callback('');
      }
      // 设置当前的装填，标识为校验中
      let validateState = 'validating';
      // 调用async-validator的方法
      let validator = new schema({
        [key]: rules
      });
      // 校验
      validator.validate(
          {
            [key]: fieldValue
          },
          {
            firstFields: true
          },
          (errors, fields) => {
            // 记录状态和报错信息
            validateState = !errors ? 'success' : 'error';
            let validateMessage = errors ? errors[0].message : '';
            that.form[that.authType].error[key] = validateMessage;
            callback(validateMessage);
          }
      );
    },

    // 校验全部数据
    validateAll(callback) {
      let that = this;
      return new Promise(resolve => {
        // 对当前所有表单检验
        let valid = true; // 默认通过
        let count = 0; // 用于标记是否检查完毕
        let errorArr = []; // 存放错误信息
        let curFormData = that.form[that.authType].data;
        Object.keys(curFormData).map(field => {
          that.validation(field, error => {
            // 如果回调有error
            if (error) {
              valid = false;
              errorArr.push(error);
            }
            if (++count === Object.keys(curFormData).length) {
              resolve(valid);
              if (errorArr.length) {
                this.$u.toast(errorArr[0]);
              }
              if (typeof callback == 'function') callback(valid);
            }
          });
        });
      });
    },


    // 规则校验
    validateSubmit() {
      if (!this.protocol) {
        this.$u.toast('请同意用户协议');
        return false;
      }
      return this.validateAll();
    },

    // 手机号是否输入完毕
    mobileInput(e, key) {
      this.form['bindMobile'].data.isMobileEnd = this.$u.test.mobile(this.form['bindMobile'].data.mobile);
      this.validation(key);
    },

    // 检测
    checkValue(e, key) {
      this.validation(key);
    },

    // 倒计时
    codeChange() {
      if (this.disabledCode) return;
      this.disabledCode = true;
      let n = 60;
      this.codeText = n + 's';
      const run = setInterval(() => {
        n -= 1;
        if (n < 0) {
          clearInterval(run);
        }
        this.codeText = n + 's';
        if (this.codeText < 0 + 's') {
          this.disabledCode = false;
          this.codeText = '重新获取';
        }
      }, 1000);
    },

    // 获取短信验证码
    getSmsCode(type) {
      const that = this;
      if (that.form['bindMobile'].data.isMobileEnd && !that.disabledCode) {
        that.$http(
            'common.smsSend',
            {
              mobile: that.form['bindMobile'].data.mobile,
              event: type
            },
            '获取验证码中...'
        ).then(res => {
          if (res.code === 1) {
            that.codeChange();
            that.$u.toast('验证码已发送，请注意查收短信');
          } else {
            that.$u.toast(res.msg);
          }
        });
      } else {
        that.$u.toast('请稍后再试');
      }
    },

    // 5.绑定手机
    async bindMobileSubmit() {
      let that = this;
      (await that.validateSubmit()) &&
      that
          .$http(
              'user.bindMobile',
              {
                mobile: that.form['bindMobile'].data.mobile,
                code: that.form['bindMobile'].data.code,
                nickname: that.form['bindMobile'].data.nickname,
                avatar: that.form['bindMobile'].data.avatar,
              },
              '绑定中...'
          )
          .then(res => {
            if (res.code === 1) {
              that.$u.toast(res.msg);
              that.closeAuthModal();
              that.getUserInfo();
            }
          });
    },

  }
};
</script>

<style lang="scss" scoped>
@keyframes title-animation {
  0% {
    font-size: 32rpx;
  }

  100% {
    font-size: 36rpx;
  }
}

.avatar_box{
  display: flex;
  flex-direction: column;
  align-items: center;
  .join_us{
    font-size: 34rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #444;
  }
  .get_avatar{
    button{
      display: flex;
      flex-direction: column;
      padding: 0;
      background: none;
      width: auto !important;
      &:after{
        display: none;
      }
    }
    .avatar{
      width: 140rpx;
      height: 140rpx;
      border-radius: 70rpx;
      background-color:#bebebe;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .text{
      margin-top: 15rpx;
      font-weight: bold;
      font-size: 24rpx;
    }
  }
}

.login_input{
  .item{
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    align-items: center;
    .item_l{
      display: flex;
      flex-direction: column;
      font-size: 26rpx;
      .item_l_tit{
        text-align: left;
      }
      input{
        width: 400rpx;
        margin-top: 20rpx;
        font-size: 26rpx;
        text-align: left;
        border-bottom: 1rpx solid #b4b4b4;
        height: 70rpx;
      }
      .note{
        margin-top: 10rpx;
        font-size: 20rpx;
      }
    }
    .item_r{
      font-size: 26rpx;
      font-weight: bold;
      button{
        background: none;
        font-size: 26rpx;
        padding: 0;
        &:after{
          display: none;
        }
      }
    }
  }
}

.form-wrap {
  .form-item {
    display: flex;
    flex-direction: column;
    font-size: 28rpx;
    padding: 20rpx 0;
    color: $u-main-color;
    box-sizing: border-box;
    line-height: $u-form-item-height;
    width: 100%;
    .item-title {
      width: 140rpx;
      font-size: 30rpx;
      color: #444;
      font-weight: 600;
      text-align: left;
    }
    .message-error {
      text-align: left;
      font-size: 24rpx;
      line-height: 24rpx;
      color: $u-type-error;
      margin-top: 12rpx;
      margin-left: 120rpx;
    }
  }
}

.login-wrap {
  padding: 50rpx 34rpx;
  min-height: 600rpx;
  background-color:#fff;
  border-radius: 20rpx 20rpx 0 0;

  .head-box {
    .head-title {
      min-width: 160rpx;
      font-size: 36rpx;
      font-weight: bold;
      color: #444;
      line-height: 36rpx;
    }
    .head-title-active {
      width: 160rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #444;
      line-height: 36rpx;
    }
    .head-title-animation {
      animation-name: title-animation;
      animation-duration: 0.1s;
      animation-timing-function: ease-out;
      animation-fill-mode: forwards;
    }
    .head-title-line {
      position: relative;
      &::before {
        content: '';
        width: 1rpx;
        height: 34rpx;
        background-color:#bebebe;
        position: absolute;
        left: -30rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .head-subtitle {
      font-size: 26rpx;
      font-weight: 400;
      color: #444;
      text-align: left;
      display: flex;
    }
  }
  .code-btn[disabled] {
    background-color:#bebebe;
  }

  .code-btn-start {
    width: 160rpx;
    line-height: 56rpx;
    border: 1rpx solid #4654FD;
    border-radius: 28rpx;
    font-size: 26rpx;
    font-weight: 400;
    color: #444;
    opacity: 0.5;
  }

  .forgot-btn {
    width: 160rpx;
    line-height: 56rpx;
    font-size: 30rpx;
    font-weight: 500;
    color: #444;
  }

  .code-btn-end {
    opacity: 1 !important;
  }

  .login-btn-start {
    width: 158rpx;
    line-height: 56rpx;
    background: linear-gradient(90deg, #1B2096, #4654FD);
    border-radius: 28rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #444;
  }

  .type-btn {
    padding: 20rpx;
    margin: 40rpx auto;
    width: 200rpx;
    font-size: 30rpx;
    font-weight: 500;
    color: #444;
  }

  .auto-login-box {
    width: 100%;
    margin: 50rpx 0;

    .auto-login-img {
      width: 68rpx;
      height: 68rpx;
      border-radius: 50%;
      margin: 0 30rpx;
    }
  }

  .agreement-box {
    .protocol-check {
      transform: scale(0.7);
    }
    .agreement-text {
      font-size: 26rpx;
      font-weight: 500;
      color: #444;

      .tcp-text {
        color: #444;
      }
    }
  }

  .join_float{
    width: 90%;
    display: flex;
    flex-direction: column;
  }
  .join_float .join_confirm{
    width: 100%;
    border: 1rpx solid #696969;
    height: 80rpx;
    font-size: 26rpx;
    font-weight: bold;
    margin: 0 auto 30rpx auto;
    line-height: 80rpx;
  }
}



</style>











